package com.aizu.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.aizu.common.Constant;
import com.aizu.service.SmsService;
import com.isp.wxchat.controller.WeixinController;
import com.isp.wxchat.model.WxUser;

@SessionAttributes({ CommonController.MASTER, CommonController.RENTER })
public class CommonController extends WeixinController {

	private Logger log = Logger.getLogger(this.getClass());

	public final static String MASTER = "master";
	public final static String RENTER = "renter";

	@Autowired
	protected SmsService smsService;

	/**
	 * 取fromUserName<br />
	 * 重写了父类的方法，因为现在用了两个公众号，房主与房客登陆后保存的key不一样<br />
	 * 房主保存在master，房客保存在renter
	 * 
	 * @param request
	 * @return
	 */
	protected String getFromUserName(HttpServletRequest request) {
		String namespace = super.getNamespace(request);// "/mvc/master"或者"/mvc/renter"

		String fromUserName = (String) request.getAttribute("fromUserName");
		if (StringUtils.isBlank(fromUserName)) {
			fromUserName = request.getParameter("fromUserName");
		}
		if (StringUtils.isBlank(fromUserName)) {
			WxUser user = null;
			if ("master".equals(namespace))
				user = (WxUser) request.getSession().getAttribute("master");
			else if ("renter".equals(namespace))
				user = (WxUser) request.getSession().getAttribute("renter");
			if (null != user) {
				fromUserName = user.getOpenid();
			}
		}
		return fromUserName;
	}

	/**
	 * 获取某街道
	 * 
	 * @param departmentId
	 *            街道id
	 * @return
	 */
	protected Map<String, Object> getDepartment(String departmentId) {
		Map<String, Map<String, Object>> departmentMap = (Map<String, Map<String, Object>>) servletContext
				.getAttribute(Constant.DEPARTMENT_MAP);
		return departmentMap.get(departmentId);
	}

	/**
	 * 获取某街道的信息
	 * 
	 * @param departmentId
	 *            街道id
	 * @param key
	 *            属性名。ie: name/REATE_DATE
	 * @return
	 */
	protected Object getDepartmentValue(String departmentId, String key) {
		Map<String, Object> department = getDepartment(departmentId);
		if (null == department) {
			return null;
		}
		return department.get(key);
	}

	/**
	 * 获取某小区
	 * 
	 * @param communityId
	 *            小区id
	 * @return
	 */
	protected Map<String, Object> getCommunity(String communityId) {
		Map<String, Map<String, Object>> communityMap = (Map<String, Map<String, Object>>) servletContext
				.getAttribute(Constant.COMMUNITY_MAP);
		return communityMap.get(communityId);
	}

	/**
	 * 获取某小区的信息
	 * 
	 * @param communityId
	 *            小区id
	 * @param key
	 *            属性名。ie: name/address/remark
	 * @return
	 */
	protected Object getCommunityValue(String communityId, String key) {
		Map<String, Object> community = getCommunity(communityId);
		if (null == community) {
			return null;
		}
		return community.get(key);
	}

	/**
	 * list转map
	 * 
	 * @param list
	 * @return
	 */
	protected Map<String, Map<String, Object>> list2Map(List<Map<String, Object>> list) {
		Map<String, Map<String, Object>> map = new HashMap<String, Map<String, Object>>();
		for (Map<String, Object> m : list) {
			map.put(m.get("id") + "", m);
		}
		return map;
	}

	/**
	 * 从areaList中取出所需
	 * 
	 * @param prentId
	 * @param level
	 * @return
	 */
	protected List<Map<String, Object>> findArea(Integer prentId, Integer level) {
		List<Map<String, Object>> allAreaList = (List<Map<String, Object>>) servletContext
				.getAttribute(Constant.AREA_LIST);
		List<Map<String, Object>> areaList = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> area : allAreaList) {
			if (((Integer) area.get("prent_id")) == prentId && ((Integer) area.get("area_level")) == level)
				areaList.add(area);
		}
		return areaList;
	}

	/**
	 * 从streetList中取出所需
	 * 
	 * @param area
	 * @return
	 */
	protected List<Map<String, Object>> findStreet(String area) {
		List<Map<String, Object>> allStreetList = (List<Map<String, Object>>) servletContext
				.getAttribute(Constant.STREET_LIST);
		List<Map<String, Object>> streetList = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> street : allStreetList) {
			if (area.equals(street.get("area")))
				streetList.add(street);
		}
		return streetList;
	}

	/**
	 * 从departmentList中取出所需
	 * 
	 * @param street_id
	 * @return
	 */
	protected List<Map<String, Object>> findDept(Integer street_id) {
		List<Map<String, Object>> allDeptList = (List<Map<String, Object>>) servletContext
				.getAttribute(Constant.DEPARTMENT_LIST);
		List<Map<String, Object>> deptList = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> dept : allDeptList) {
			if (((Integer) dept.get("street_id")) == street_id)
				deptList.add(dept);
		}
		return deptList;
	}

	/**
	 * 从communityList中取出所需
	 * 
	 * @param dept_id
	 * @return
	 */
	protected List<Map<String, Object>> findCommunity(Integer dept_id) {
		List<Map<String, Object>> allCommunityList = (List<Map<String, Object>>) servletContext
				.getAttribute(Constant.COMMUNITY_LIST);
		List<Map<String, Object>> communityList = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> community : allCommunityList) {
			if (((Integer) community.get("dept_id")) == dept_id)
				communityList.add(community);
		}
		return communityList;
	}

	/**
	 * 生成4位随机码
	 * 
	 * @param phone 手机号
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getCode.htm")
	@ResponseBody
	protected String getCode(@RequestParam String phone, HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		// 验证之前的验证码，看是否超过3分钟，不超过不重发
		final Date sessionRandomCodeTime = (Date) session.getAttribute(Constant.RANDOM_CODE_TIME);
		if (null != sessionRandomCodeTime && DateUtils.addMinutes(sessionRandomCodeTime, 3).after(new Date())) {
			log.info("上次发的验证码" + session.getAttribute(Constant.RANDOM_CODE) + "还没超过3分钟");
			return Boolean.TRUE.toString();
		}

		final String randomCode = RandomStringUtils.randomNumeric(4);
		session.setAttribute(Constant.RANDOM_CODE, randomCode);
		session.setAttribute(Constant.RANDOM_CODE_TIME, new Date());
		log.info("验证码" + randomCode + "已发送到手机" + phone);
		Boolean result = false;
		try {
			result = smsService.saveSms(null, phone, "本次验证码为" + randomCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	/**
	 * 验证随机码
	 * 
	 * @param randomCode
	 *            验证码
	 * @param clearCode
	 *            是否清除验证码
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/validateCode.htm")
	@ResponseBody
	protected String validateCode(@RequestParam(value = "code") String randomCode, boolean clearCode,
			HttpServletRequest request) {
		final HttpSession session = request.getSession();
		final String sessionRandomCode = (String) session.getAttribute(Constant.RANDOM_CODE);
		log.info("开始对比验证码" + randomCode + "(pass) vs " + sessionRandomCode + "(session)");
		if (null != randomCode && randomCode.equals(sessionRandomCode)) {
			log.info("验证通过");
			if (clearCode) {
				log.info("清除session中的验证码");
				session.removeAttribute(Constant.RANDOM_CODE);
				session.removeAttribute(Constant.RANDOM_CODE_TIME);
			}
			return Boolean.TRUE.toString();
		}
		log.info("验证码不正确");
		return Boolean.FALSE.toString();
	}

}
